package com.zsguan.z.zwidget4andr.text;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint.Style;
import android.support.annotation.NonNull;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;

import java.lang.reflect.Field;

/*
 * StrokeTextView的目标是给文字描边
 * 实现方法是两个TextView叠加,只有描边的TextView为底,实体TextView叠加在上面
 * 看上去文字就有个不同颜色的边框了
 */
public class StrokeText2View extends TextView {

    private TextPaint m_TextPaint;

    public StrokeText2View(Context context) {
        super(context);
        init();
    }

    public StrokeText2View(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public StrokeText2View(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public void init() {
        m_TextPaint = this.getPaint();
    }

    /**
     * (non-Javadoc)
     *
     * @see android.widget.TextView#onDraw(android.graphics.Canvas)
     */
    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        // 描外层

        setTextColorUseReflection(Color.BLUE);
        m_TextPaint.setStrokeWidth(20);  // 描边宽度
        m_TextPaint.setStyle(Style.FILL_AND_STROKE); //描边种类
        m_TextPaint.setFakeBoldText(true); // 外层text采用粗体
        m_TextPaint.setShadowLayer(0, 0, 0, 0); //字体的阴影效果，可以忽略
        super.onDraw(canvas);


        // 描内层，恢复原先的画笔

        setTextColorUseReflection(Color.RED);
        m_TextPaint.setStrokeWidth(0);
        m_TextPaint.setStyle(Style.FILL);
        m_TextPaint.setFakeBoldText(false);
        m_TextPaint.setShadowLayer(0, 0, 0, 0);
        super.onDraw(canvas);
    }

    private void setTextColorUseReflection(int color) {
        Field textColorField;
        try {
            textColorField = TextView.class.getDeclaredField("mCurTextColor");
            textColorField.setAccessible(true);
            textColorField.set(StrokeText2View.this, color);
            textColorField.setAccessible(false);
        } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }

        m_TextPaint.setColor(color);
    }


}